package cc.xsubj.trading.inventory;

import java.util.ArrayList;
import java.util.List;

import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.geom.Rectangle;

import cc.xsubj.engine.Globals;
import cc.xsubj.trading.entity.InventoryItem;

public class InventoryGrid
{
    final int gridWidth;
    final int gridHeight;
    public static final int defaultGridWidth = 5;
    public static final int defaultGridHeight = 8;
    public static final int itemWidth = 24;
    public static final int itemHeight = 24;
    public static final int itemXSpacing = 4;
    public static final int itemYSpacing = 4;
    final int width;
    final int height;
    final int x;
    final int y;
    private final List<InventorySlot> slots;
    
    public InventoryGrid(int x, int y, int gridWidth, int gridHeight)
    {
        this.x = x;
        this.y = y;
        this.gridWidth = gridWidth;
        this.gridHeight = gridHeight;
        
        this.width = gridWidth * (itemWidth + itemXSpacing);
        this.height = gridHeight * (itemHeight + itemYSpacing);
        
        this.slots = new ArrayList<InventorySlot>(gridWidth * gridHeight);
        
        for (int j = 0; j < gridHeight; j++)
        {
            for(int i = 0; i < gridWidth; i++)
            {
            
                Rectangle slotRect = new Rectangle(i * (itemWidth + itemXSpacing) + x, j * (itemHeight + itemYSpacing) + y, itemWidth, itemHeight);
                InventorySlot slot = new InventorySlot(slotRect, i, j);
                slots.add(slot);
            }
        }
        
    }
    
    public void render(Graphics g)
    {
        g.pushTransform();
        
        g.scale(Globals.scaleX, Globals.scaleY);
        g.setColor(Color.red);
        g.setLineWidth(3);
        
        for (InventorySlot slot : slots)
        {
            g.draw(slot.getBounds());
        }
        
        g.popTransform();
    }
    
    public boolean containsPoint(float x, float y)
    {
        return (x > this.x && x < this.x+this.width && y > this.y && y < this.y+this.height);
    }
    
    public InventorySlot getSlotForItem(InventoryItem item)
    {
        return getSlotAtPosition(item.x, item.y);
    }
    
    public InventorySlot getSlotAtPosition(float x, float y)
    {
        for (InventorySlot slot : slots)
        {
            if(slot.getBounds().contains(x, y))
            {
                return slot;
            }
        }
        return null;
    }
    
    public int getInventoryIndexFromCoords(int x, int y)
    {
        return y*gridWidth + x;
    }
    
    public List<InventorySlot> getSlots()
    {
        return slots;
    }
}
